package customGUI.selectors;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.swing.JComboBox;
import javax.swing.JComponent;

import db.DBConnectionFactory;
import db.DBConnector;

public class ComboBoxAccountSelector extends AccountSelector {

	public ComboBoxAccountSelector(String label) {
		super(label,new JComboBox<String>());
	}

	@Override
	public String getSelectedUsername() {
		JComboBox comboBox = (JComboBox)selector;
		
		if(comboBox.getSelectedIndex() < 0)
			return null;
		
		StringTokenizer tokenizer = new StringTokenizer(comboBox.getSelectedItem().toString(), "-");
			return tokenizer.nextToken();
	}

	@Override
	protected ArrayList<String> retrieveAccountList() {
		ResultSet rs;
		String query = ("SELECT Username, FName, LName from useraccounts ORDER BY username");
		Connection con = DBConnectionFactory.getInstance().getConnection();
		rs = DBConnector.executeQuery(con, query);
		ArrayList<String> accountList = new ArrayList<String>();
		try {
			while(rs.next())
				accountList.add(rs.getString("username") + " - " + rs.getString("LName") + " , " + rs.getString("FName"));		
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return accountList;
	}

	@Override
	protected void setChoices(ArrayList<String> accountList) {
		JComboBox<String> comboBox = (JComboBox) selector;
		comboBox.removeAllItems();
		
		for(int i=0;i<accountList.size();i++){
			comboBox.addItem(accountList.get(i));
		}
		
	}

}
